import * as multer from 'multer';
import Express, { Request, Response } from 'express';
import { PORT } from '@/share/config';
const path = require('path');
const fs = require('fs');
interface UploadResult {
  originalname: string;
  mimetype: string;
  destination: string;
  filename: string;
  path: string;
  size: number;
  final_dir: string;
  final_host: string;
  final_file_path: string;
}

const FILE_PATH = path.join(process.cwd(), 'uploads/');
// 配置存储引擎
const storage = multer.diskStorage({
  destination: function (
    req: Request,
    file: Express.Multer.File,
    cb: (error: Error | null, destination: string) => void
  ) {
    const temp_path = path.join(FILE_PATH, 'temp/');
    // 确保目录存在，设置recursive: true时，如果目标目录的父目录不存在，Node.js会尝试创建
    fs.mkdir(temp_path, { recursive: true }, (err: Error) => {
      if (err) {
        console.error(
          `Failed to create upload directory: ${temp_path}`,
          err
        );
        return cb(err, temp_path);
      }
      cb(null, temp_path);
    });
  },
  filename: function (
    req: Request,
    file: Express.Multer.File,
    cb: (error: Error | null, filename: string) => void
  ) {
    const ext = path.extname(file.originalname); // 获取文件扩展名
    const fileName = `${Date.now()}${ext}`;
    cb(null, fileName);
  },
});

const fileFilter = (
  req: Request,
  file: Express.Multer.File,
  cb: (error: Error | null, acceptFile: boolean) => void
) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'video/mp4'];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('无效的文件类型。只允许 JPEG、PNG、MP4'), false);
  }
};

// 配置 Multer 中间件
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 30, // 大小限制
  },
}).single('file');

const uploadHandle = (
  req: Request,
  res: Response
): Promise<UploadResult> => {
  return new Promise((resolve, reject) => {
    upload(req, res, (err: Error) => {
      if (err instanceof multer.MulterError || err) {
        return reject(err.message);
      }

      const temp_file_path = req.file ? req.file.path : null;
      if (!temp_file_path) {
        return resolve(null);
      }

      const final_file_path = path.join(FILE_PATH, req.file.filename);

      fs.mkdir(FILE_PATH, { recursive: true }, (err: Error) => {
        if (err) {
          console.error(
            `Failed to create final directory: ${FILE_PATH}`,
            err
          );
          return reject('Failed to create final directory');
        }

        fs.rename(temp_file_path, final_file_path, (err: Error) => {
          if (err) {
            console.error(
              `Failed to move file from ${temp_file_path} to ${final_file_path}`,
              err
            );
            return reject('Failed to move file');
          }
        });
      });

      // if(process.env.NODE_ENV === 'production')

      const index = req.headers.host.lastIndexOf(':');
      let final_unhost;
      index >= 0
        ? (final_unhost = req.headers.host.slice(0, index))
        : (final_unhost = req.headers.host);

      resolve({
        ...req.file,
        final_host: `http://chf.lven.tech/uploads/`,
        final_file_path,
      });
    });
  });
};

export { uploadHandle, FILE_PATH };
